<template>
  <el-card shadow="never">
    <el-form label-width="auto" :inline="true" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item label="合同编号" style="width: 85%">
            <el-input
              v-model="searchForm.contractNo"
              placeholder="请输入 合同编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" style="width: 85%">
            <el-select
              v-model="searchForm.contractName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 合同名称"
              :remote-method="getContractNameList"
              size="small"
            >
              <el-option
                v-for="item in contractOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" style="width: 85%">
            <el-select
              v-model="searchForm.projectName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 项目名称"
              :remote-method="getProjectNameList"
              size="small"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商名称" style="width: 85%">
            <el-input
              v-model="searchForm.supplierDeptName"
              placeholder="请输入 供应商名称"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对账周期" style="width: 85%">
            <el-date-picker
              v-model="searchForm.reconDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对账状态" style="width: 85%">
            <el-select
              v-model="searchForm.statusList"
              placeholder="请选择 合同状态"
              size="small"
              clearable
            >
              <el-option
                v-for="item in statusListOptions"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button
            color="#1E3485"
            size="small"
            icon="Download"
            @click="getList(true)"
          >导出</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Edit"
            @click="
              toDetail(
                { title: '新建项目对账单', action: 'add' },
                'addReconcoilation'
              )
            "
            >新建</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getList();
            "
            >搜索</el-button
          >
          <el-button
            type="default"
            size="small"
            :icon="Delete"
            @click="clearAllFields"
            >清空</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      min-height="300"
      header-align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="tableData"
      size="mini"
      :loading="tableLoading"
      :pager-config="tablePage"
      style="margin-top: 1%"
    >
      <vxe-column
        v-for="column in tableColumns"
        :key="column.field"
        :field="column.field"
        :title="column.title"
        :fixed="column.fixed"
        :min-width="column.width"
        :align="column.align"
        show-overflow
      >
        <template v-if="column.field === 'status'" v-slot:default="{ row }">
          <span :style="{ color: getStatusColor(row[column.field]) }">
            {{ statusMap[row[column.field]] }}
          </span>
        </template>
        <template
          v-else-if="column.field === 'reconciliationDate'"
          v-slot:default="{ row }"
        >
          {{ row.reconciliationStartDate + "至" + row.reconciliationEndDate }}
        </template>
        <template
          v-else-if="column.field === 'paymentCycle'"
          v-slot:default="{ row }"
        >
          {{ paymentCycleMap[row[column.field]] }}
        </template>
        <template
          v-else-if="column.field === 'priceType'"
          v-slot:default="{ row }"
        >
          {{ priceTypeMap[row[column.field]] }}
        </template>
        <template
          v-else-if="column.field === 'auditStatus'"
          v-slot:default="{ row }"
        >
          <span v-if="row.status === 0">待核对</span>
          <span
            v-if="row.status === 1 || ['1', '3', '4'].includes(row.auditStatus)"
          >
            <span v-if="row.auditStatus === '0'">待提交</span>
            <span v-if="row.auditStatus === '1'">审批中</span>
            <span v-if="row.auditStatus === '2'">已审核</span>
            <span v-if="row.auditStatus === '3'">审批驳回</span>
            <span v-if="row.auditStatus === '4'">撤回</span>
          </span>
          <span v-if="row.status === 2">待项目确认</span>
          <span v-if="row.status === 3">待云采确认</span>
          <span v-if="row.status === 4">项目确认驳回</span>
          <span v-if="row.status === 5">对账结算中</span>
          <span v-if="row.status === 6">对账结算完成</span>
          <span v-if="row.status === 7">云采确认完成</span>
        </template>
        <template v-else v-slot:default="{ row }">
          {{ row[column.field] }}
        </template>
      </vxe-column>
      <vxe-column title="操作" min-width="280" align="center" fixed="right">
        <template v-slot:default="{ row }">
          <vxe-button
            type="text"
            size="small"
            @click="
              toDetail(
                { id: row.id, title: row.contractName, action: 'view' },
                'viewReconcoilation'
              )
            "
          >
            查看
          </vxe-button>
          <vxe-button
            v-if="
              (row.status === 1 && ['0', '3', '4'].includes(row.auditStatus)) ||
              row.status === 0
            "
            type="text"
            size="small"
            @click="
              toDetail(
                { id: row.id, title: row.contractName, action: 'edit' },
                'editReconcoilation'
              )
            "
          >
            编辑
          </vxe-button>
          <vxe-button
            v-if="row.status === 0"
            type="text"
            size="small"
            @click="rowDelete(row)"
          >
            删除
          </vxe-button>
          <vxe-button
            v-if="row.status === 0"
            type="text"
            size="small"
            @click="
              toDetail(
                {
                  id: row.id,
                  title: row.contractName,
                  action: 'examine',
                  type: '0'
                },
                'examineReconcoilation'
              )
            "
          >
            核对
          </vxe-button>
          <vxe-button
            v-if="row.status === 2"
            type="text"
            size="small"
            @click="
              toDetail(
                {
                  id: row.id,
                  title: row.contractName,
                  action: 'examine',
                  type: '1'
                },
                'examineReconcoilation'
              )
            "
          >
            对账确认
          </vxe-button>
          <vxe-button
            v-if="row.status === 3"
            type="text"
            size="small"
            @click="
              toDetail(
                {
                  id: row.id,
                  title: row.contractName,
                  action: 'examine',
                  type: '2'
                },
                'examineReconcoilation'
              )
            "
          >
            云采确认
          </vxe-button>
          <vxe-button
            v-if="row.status === 1 && ['0', '3', '4'].includes(row.auditStatus)"
            type="text"
            size="small"
            @click="rowExamine(row.id)"
          >
            提交审批
          </vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-pager
      v-model:current-page="tablePage.currentPage"
      v-model:page-size="tablePage.pageSize"
      :layouts="[
        'Sizes',
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'FullJump',
        'Total'
      ]"
      :total="tablePage.total"
      size="mini"
      style="margin-top: 2%"
      @page-change="handlePageChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Delete, Search, Edit } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDetail } from "../hooks";
import { getSalesContractsList } from "@/api/ERP_sales";
import { getProjectList } from "@/api/ERP_public";
import {
  getReconciliationDataList,
  reconSubmitAudit,
  delReconciliationData
} from "@/api/ERP_settlement";
import { getDict } from "@/api/utils";
import {http} from "@/utils/http";
import {baseUrlApi} from "@/store/utils";

///////////////////////// 数据准备 /////////////////////////
// 路由跳转
const { toDetail, router } = useDetail();
// 搜索表单
let searchForm = reactive({
  contractNo: "",
  contractName: "",
  projectName: "",
  supplierDeptName: "",
  reconDate: "",
  statusList: ""
});
// 清空按钮点击事件
const clearAllFields = () => {
  // 重置searchForm对象的所有属性
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "signDate") {
        // searchForm[key] = [];
        searchForm[key] = null;
      } else {
        searchForm[key] = "";
      }
    }
  }
};
// 合同名称选择
let contractOptions = ref([]);
// 合同名称列表下拉框
const getContractNameList = (query: string) => {
  getSalesContractsList({
    pageIndex: 1,
    pageSize: 10,
    contractType: "0",
    contractName: query
  }).then(response => {
    contractOptions.value = (response as any).data.records.map(item => ({
      label: item.contractName,
      value: item.contractName
    }));
  });
  if (query) {
    setTimeout(() => {
      getSalesContractsList;
    }, 1500);
  }
};
// 项目名称选择
let projectOptions = ref([]);
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query,
    contractMethod:0
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
// 对账状态选择 - 暂时写死
let statusListOptions = ref([
  { label: "未对账", value: "0, 1, 2, 4" },
  { label: "已对账未结算", value: "5, 3, 7" },
  { label: "已对账已结算", value: "6" }
]);
// 状态字段颜色
const getStatusColor = status => {
  switch (status.toString()) {
    case "0":
      return "red";
    case "1":
      return "red";
    case "2":
      return "red";
    case "3":
      return "orange";
    case "4":
      return "red";
    case "5":
      return "orange";
    case "6":
      return "green";
    case "7":
      return "orange";
    default:
      return "black";
  }
};
// 表格字段翻译 - 对账状态
let statusMap = {};
// 获取字典值 - 对账状态
async function getStatusMap() {
  let params: ApiParams = {};
  params.key = "reconciliation_type";
  try {
    const response: ApiResponse = await getDict(params);
    statusMap = response.data;
  } catch (error) {
    ElMessage.error("获取合同状态列表失败");
  }
}
// 表格字段翻译 - 付款周期
let paymentCycleMap = {};
// 获取字典值 - 付款周期
async function getPaymentCycleMap() {
  let params: ApiParams = {};
  params.key = "payment_cycle";
  try {
    const response: ApiResponse = await getDict(params);
    paymentCycleMap = response.data;
  } catch (error) {
    ElMessage.error("获取付款周期列表失败");
  }
}
// 表格字段翻译 - 价格类型
let priceTypeMap = {};
// 获取字典值 - 价格类型
async function getPriceTypeMap() {
  let params: ApiParams = {};
  params.key = "price_type";
  try {
    const response: ApiResponse = await getDict(params);
    priceTypeMap = response.data;
  } catch (error) {
    ElMessage.error("获取价格类型列表失败");
  }
}
// TODO - 表格状态列字典相关
///////////////////////// 数据展示 /////////////////////////
// 表格数据
let tableData = ref([]);
let tableLoading = ref(false);
// 表格列
const tableColumns = ref([
  {
    field: "contractNo",
    title: "合同编号",
    fixed: "left",
    width: 200
  },
  {
    field: "contractName",
    title: "合同名称",
    fixed: "left",
    width: 200
  },
  {
    field: "projectName",
    title: "项目名称",
    width: 200
  },
  {
    field: "supplierDeptName",
    title: "供应商",
    width: 200
  },
  {
    field: "supplyIncludingTaxTotalPrice",
    title: "含税总价（元）",
    width: 120,
    align: "right"
  },
  {
    field: "reconciliationPrice",
    title: "确认含税总价（元）",
    width: 150,
    align: "right"
  },
  {
    field: "priceType",
    title: "价格类型",
    width: 120,
    align: "center"
  },
  {
    field: "supplyNum",
    title: "验收清单",
    width: 120,
    align: "center"
  },
  {
    field: "reconciliationDate",
    title: "对账周期",
    width: 200,
    align: "center"
  },
  {
    field: "createdAt",
    title: "创建时间",
    width: 120,
    align: "center"
  },
  {
    field: "paymentCycle",
    title: "付款周期",
    width: 120,
    align: "center"
  },
  {
    field: "status",
    title: "对账状态",
    width: 120,
    align: "center"
  },
  {
    field: "auditStatus",
    title: "状态",
    width: 120,
    align: "center"
  }
]);
// 表格分页配置
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
// 获取列表
async function getList(isExport) {

  let params: ApiParams = {};

  params.contractMethod = 0
  if (searchForm.contractNo) params.contractNo = searchForm.contractNo;
  if (searchForm.contractName) params.contractName = searchForm.contractName;
  if (searchForm.projectName) params.projectName = searchForm.projectName;
  if (searchForm.supplierDeptName)
    params.supplierDeptName = searchForm.supplierDeptName;
  if (searchForm.statusList) params.statusList = searchForm.statusList;
  if (searchForm.reconDate) {
    params.reconciliationStartDate = searchForm.reconDate[0];
    params.reconciliationEndDate = searchForm.reconDate[1];
  }

  if(isExport) {
    await http.request('get',baseUrlApi("reconciliation/export/file"), {params})
    return
  }
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  tableLoading.value = true;
  try {
    const response: ApiResponse = await getReconciliationDataList(params);
    tableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取列表失败");
  } finally {
    tableLoading.value = false;
  }
}
// 删除按钮
async function rowDelete(row) {
  ElMessageBox.confirm("确认删除该对账单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params: ApiParams = {};
      params.id = row.id;
      const response: ApiResponse = await delReconciliationData(params);
      if (response.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error("删除失败: " + response.msg);
      }
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
}
// 提交审批按钮
const rowExamine = id => {
  ElMessageBox.confirm("确认提交该合同审批吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params: ApiParams = {};
      params.id = id;
      const response: ApiResponse = await reconSubmitAudit(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        getList();
      } else {
        ElMessage.error("提交失败：" + response.msg);
      }
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
};
// 初始化
onMounted(async () => {
  // 数据字典
  getStatusMap();
  getPaymentCycleMap();
  getPriceTypeMap();
  // 获取列表
  getList();
});
</script>

<style lang="scss" scoped></style>
